﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using MRecorder;
using AxPHONIC_USBLib;
using System.Collections;
using System.Runtime.InteropServices;
using System.Net;
using System.Diagnostics;
using System.Configuration;

namespace 录音客户端
{
    public partial class Form1 : Form
    {
        private ArrayList ChannelArray;
        String Port = ConfigurationManager.AppSettings["port"];//端口
        String ServerIP = ConfigurationManager.AppSettings["ServerIP"];//服务器IP
        public Form1()
        {
            InitializeComponent();
        }


        private void ShowError(string err)
        {
            MessageBox.Show(err, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void ShowBalloonTip(string text)
        {
            this.notifyIcon1.ShowBalloonTip(1, this.Text, text, ToolTipIcon.Info);
            // base.Click += new EventHandler(this.notifyIcon1_Click);
        }
        #region 电话录音

        private enum eColums
        {
            COL_LINE_ID,
            COL_LINE_TYPE,
            COL_STATE,
            COL_CALLER,
            COL_DTMF,
            COL_MAX
        }

        private enum EnumStep
        {
            STEP_IDLE,
            STEP_WELCOME,
            STEP_INPUT_COUNT,
            STEP_INPUT_PASS,
            STEP_CONSULT_DETAIL,
            STEP_GOODBY
        }
        private void OnCallId(object sender, _DPhonic_usbEvents_CallIdEvent e)
        {
            Channel channel = this.GetChannel(e.uboxHandle);
            if (channel != null)
            {
                channel._callerNumber = e.callerNumber;
                this.ShowBalloonTip(channel._callerNumber + "来电");
                this.Linelist.Items[channel._lineID].SubItems[3].Text = channel._callerNumber;
                 channel._step = 1L;
            }
        }

        private void OnCallOutFinish(object sender, _DPhonic_usbEvents_CallOutFinishEvent e)
        {
            Channel channel = this.GetChannel(e.uboxHandle);
            if (channel != null)
            {
                this.Linelist.Items[channel._lineID].SubItems[2].Text = "呼叫完成";
            }
        }

        private void OnDeviceAlarm(object sender, _DPhonic_usbEvents_DeviceAlarmEvent e)
        {
            Channel channel = this.GetChannel(e.uboxHandle);
            if (channel != null)
            {
                string text = "UBOX ";
                text = text + channel._lineID.ToString();
                switch (e.param)
                {
                    case 1:
                        text = text + "未能找到ubox 的MIC 设备!";
                        break;

                    case 2:
                        text = text + "未能打开ubox 的MIC 设备!";
                        break;

                    case 3:
                        text = text + "未能打开ubox 的放音设备!";
                        break;

                    case 4:
                        text = text + "设备故障!";
                        break;
                }
                ShowError(text);
            }
        }

        private void OnDeviceError(object sender, _DPhonic_usbEvents_DeviceErrorEvent e)
        {
            Channel channel = this.GetChannel(e.uboxHandle);
            if (channel != null)
            {
                ShowError("UBOX " + channel._lineID.ToString() + " 设备错误!");
            }
        }

        private void OnDtmfKey(object sender, _DPhonic_usbEvents_DtmfKeyEvent e)
        {
            Channel channel = this.GetChannel(e.uboxHandle);
            if (channel != null)
            {
                channel._strDTMF = channel._strDTMF + ((char)e.dtmfCode);
                this.Linelist.Items[channel._lineID].SubItems[4].Text = channel._strDTMF;
            }
        }

        private void OnHangup(object sender, _DPhonic_usbEvents_HangUpEvent e)
        {
            Channel channel = this.GetChannel(e.uboxHandle);
            if (channel != null)
            {
                this.Linelist.Items[channel._lineID].SubItems[2].Text = "空闲";
                this.Linelist.Items[channel._lineID].SubItems[3].Text = "";
                this.Linelist.Items[channel._lineID].SubItems[4].Text = "";
                channel._ringCount = 0;
                if (channel._bRecording)
                {
                    this.Phonic_usb.StopRecord(channel._handle);
                    channel._bRecording = false;
                }
            }
        }

        private void OnHookOff(object sender, _DPhonic_usbEvents_HookOffEvent e)
        {
            Channel channel = this.GetChannel(e.uboxHandle);
            if (channel != null)
            {

                this.Linelist.Items[channel._lineID].SubItems[2].Text = "摘机";
                this.Linelist.Items[channel._lineID].SubItems[3].Text = "";
                this.Linelist.Items[channel._lineID].SubItems[4].Text = "";
                channel._bRecording = true;
                string fileName = this.GetFileName(channel._lineID, channel._callerNumber);
                this.Phonic_usb.RecordFile(channel._handle, fileName, 0);
                //接听来电
                Get2Http("http://" + ServerIP + ":" + Port + "/ui/jietinglaidian.aspx?phone=" + channel._callerNumber, System.Text.Encoding.UTF8);

                string customerinfo = Get2Http("http://" + ServerIP + ":" + Port + "/ui/getCallNumInfo.aspx?phone=" + channel._callerNumber, System.Text.Encoding.UTF8);
                if (customerinfo.Trim().Length > 0)
                {
                    customerinfo += "来电，是否";
                }
                StartKiller(10);//无操作10秒后关闭弹出窗口
                //接听弹窗
                if (DialogResult.OK == MessageBox.Show(customerinfo + "打开来电速录?", "确认", MessageBoxButtons.OKCancel))
                {
                    Process.Start("IEXPLORE.EXE", "http://" + ServerIP + ":" + Port + "/ui/callin.aspx?phone=" + channel._callerNumber + "&close=close");
                }




            }
        }

        private void OnPlayEnd(object sender, _DPhonic_usbEvents_PlayEndEvent e)
        {
            Channel channel = this.GetChannel(e.uboxHandle);
            if (channel != null)
            {
                this.Linelist.Items[channel._lineID].SubItems[2].Text = "PlayEnd";
            }
        }

        private void OnPlugIn(object sender, _DPhonic_usbEvents_PLugInEvent e)
        {
            Channel channel = new Channel();
            channel.Inital(e.uboxHandle, this.ChannelArray.Count);
            int productID = this.Phonic_usb.GetProductID(e.uboxHandle);
            string str = "";
            switch (productID)
            {
                case 1:
                    str = "FI3102A";
                    break;

                case 2:
                    str = "FI3002B";
                    break;

                case 3:
                    str = "FI3001B";
                    break;

                case 4:
                    str = "FI3101A";
                    break;

                default:
                    str = "unkown product";
                    break;
            }
            ListViewItem item = new ListViewItem(new string[] { this.ChannelArray.Count.ToString(), str, "空闲", "", "" });
            item.Tag = channel;
            this.Linelist.Items.Add(item);
            this.ChannelArray.Add(channel);
        }

        private void OnPlugOut(object sender, _DPhonic_usbEvents_PlugOutEvent e)
        {
            Channel channel = this.GetChannel(e.uboxHandle);
            if (channel != null)
            {
                foreach (ListViewItem item in this.Linelist.Items)
                {
                    if (((Channel)item.Tag) == channel)
                    {
                        item.Remove();
                        this.ChannelArray.Remove(channel);
                        break;
                    }
                }
                for (int i = 0; i < this.Linelist.Items.Count; i++)
                {
                    this.Linelist.Items[i].SubItems[0].Text = i.ToString();
                }

            }
        }

        private void OnRing(object sender, _DPhonic_usbEvents_RingEvent e)
        {
            Channel channel = this.GetChannel(e.uboxHandle);
            if (channel != null)
            {
                channel._ringCount++;
                string str = "振铃 ";
                str = str + channel._ringCount.ToString();
                this.Linelist.Items[channel._lineID].SubItems[2].Text = str;
                //未接来电
                Get2Http("http://" + ServerIP + ":" + Port + "/ui/weijielaidian.aspx?phone=" + channel._callerNumber, System.Text.Encoding.UTF8);

            }
        }

        private void OnRingCancel(object sender, _DPhonic_usbEvents_RingCancelEvent e)
        {
            Channel channel = this.GetChannel(e.uboxHandle);
            if (channel != null)
            {
                this.Linelist.Items[channel._lineID].SubItems[2].Text = "空闲";
                this.Linelist.Items[channel._lineID].SubItems[3].Text = "";
                this.Linelist.Items[channel._lineID].SubItems[4].Text = "";
                channel._ringCount = 0;
            }
        }

        private Channel GetChannel(int handle)
        {
            foreach (Channel channel in this.ChannelArray)
            {
                if (channel._handle == handle)
                {
                    return channel;
                }
            }
            return null;
        }

        private string GetFileName(int lineID, string CallPhoneNum)
        {
            DateTime now = DateTime.Now;
            //string path = @"c:\\电话录音\\";
            string path = Application.StartupPath.ToLower();
            string str = now.Year.ToString("d4");
            path = path + @"\\电话录音\\" + str;
            str = str + now.Month.ToString("d2");
            path = path + @"\" + now.Month.ToString("d2");
            str = str + now.Day.ToString("d2");
            path = (path + @"\" + now.Day.ToString("d2")) + @"\" + lineID.ToString("d3");
            Directory.CreateDirectory(path);
            path = path + @"\";
            str = (((str + "-") + now.Hour.ToString("d2") + now.Minute.ToString("d2")) + now.Second.ToString("d4") + "-") + CallPhoneNum + ".wav";

            return (path + str);
        }
        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            
            ShowBalloonTip("启动服务");
            if (this.Phonic_usb.OpenDevice(0) != 0)
            {
                ShowError("连接设备错误");
            }
            else
            {
                ShowBalloonTip("加载电话驱动");
                this.ChannelArray = new ArrayList();
                this.Linelist.GridLines = true;
                this.Linelist.View = View.Details;
                this.Linelist.FullRowSelect = true;
                this.Linelist.Columns.Add("ID", 60);
                this.Linelist.Columns.Add("类型", 60);
                this.Linelist.Columns.Add("状态", 60);
                this.Linelist.Columns.Add("主叫", 100);
                this.Linelist.Columns.Add("按键", 100);
            }
            ShowBalloonTip("启动完毕，开始工作");
            //登录
            Process.Start("IEXPLORE.EXE", "http://" + ServerIP + ":" + Port + "/ui/login.aspx");


        }







        #region 抓取URL地址获取内容
        /// <summary>
        /// 传递参数
        /// </summary>
        /// <param name="url"></param>
        /// <param name="en"></param>
        /// <returns></returns>
        public static string Get2Http(string url, Encoding en)
        {
            try
            {
                HttpWebRequest request = null;
                request = (HttpWebRequest)WebRequest.Create(url);
                request.CookieContainer = new CookieContainer();
                request.Timeout = 20000;
                request.KeepAlive = false;
                request.AllowAutoRedirect = true;
                request.Method = "GET";
                request.ContentType = "application/x-www-form-urlencoded";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), en);
                string str = reader.ReadToEnd();
                reader.Close();
                return str;
            }
            catch (SystemException er)
            {

                return "";
            }

        }

        #endregion











        #region 定時自動关闭MessageBox視窗小技巧
        [DllImport("user32.dll", EntryPoint = "FindWindow", CharSet = CharSet.Auto)]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);




        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int PostMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
        public const int WM_CLOSE = 0x10;

        private void StartKiller(int getTime)
        {
            Timer SetTimer = new Timer();         // 宣告一個Timer物件，名稱為 SetTimer 
            SetTimer.Interval = (getTime * 1000);          //x秒后启动
            SetTimer.Tick += new EventHandler(SetTimer_Tick);   // 建立一个触发Tick事件 
            SetTimer.Start();                     // 启动Timer (即SetTimer 开始启动 ) 
        }


        void SetTimer_Tick(object sender, EventArgs e)
        {
            KillMessageBox();         // 執行把 MessageBox 刪除 (即让MessageBox消失) 
            ((Timer)sender).Stop();    //停止時間。記得要转型为 Timer 型別 
        }


        private void KillMessageBox()
        {
            try
            {
                // 按照MessageBox的标题，找出Messagebox这个视窗  
                IntPtr ptr = FindWindow(null, "确认");
                if (ptr != IntPtr.Zero)    // 此表示只要 ptr 不为空值的内容时 
                {
                    //找到则关闭 MessageBox 視窗  
                    PostMessage(ptr, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }


        #endregion

        #region 超链接
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("IEXPLORE.EXE", "http://" + ServerIP + ":" + Port + "/ui/login.aspx");

        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("IEXPLORE.EXE", "http://" + ServerIP + ":" + Port + "/ui/callin.aspx?close=close");
        }
        #endregion


        void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Normal)
            {
                this.WindowState = FormWindowState.Minimized;
                this.Hide();
            }
            else if (this.WindowState == FormWindowState.Minimized)
            {

                this.Show();
                this.WindowState = FormWindowState.Normal;
                this.Activate();
                this.TopMost = true;
            }


        }
        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            if (base.WindowState == FormWindowState.Minimized)
            {
                base.Hide();
                this.notifyIcon1.Visible = true;
            }
            if (base.WindowState == FormWindowState.Maximized)
            {
            }
        }


        private void MainForm_Closing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult.Yes == MessageBox.Show("程序正在使用中,确认退出?", "确认退出", MessageBoxButtons.YesNo))
            {
                this.Phonic_usb.CloseDevice();

                //把包含酒店好帮手的窗口全部关闭
                Process[] allProcess = Process.GetProcessesByName("IEXPLORE");
                foreach (Process pc in allProcess)
                {

                    if (pc.MainWindowTitle.Contains("酒店好帮手"))
                    {
                        pc.Kill();
                    }
                }
            }
            else
            {
                e.Cancel = true;
            }
        }
        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.Activate();
            this.TopMost = true;
        }

        private void 隐藏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.notifyIcon1.Visible = false;
            this.Close();
            this.Dispose();
            Application.Exit();
        }

        private void btnSet_Click(object sender, EventArgs e)
        {
            Form FrmSet = new serverInfo();
            FrmSet.ShowDialog();
            //重新加载
            Port = ConfigurationManager.AppSettings["port"];//端口
            ServerIP = ConfigurationManager.AppSettings["ServerIP"];//服务器IP
        }

    }
}
